from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, update
from typing import Optional
from module_user.entity.do.bg_affiliate_commission_do import BgAffiliateCommission
from datetime import datetime
from decimal import Decimal


class BgAffiliateCommissionDao:
    """推广返利记录DAO"""

    async def create_commission_record(self, db: AsyncSession, inviter_id: int, invitee_id: int, 
                               order_id: int, order_amount: Decimal, commission_rate: Decimal, auto_commit=True) -> BgAffiliateCommission:
        """创建返利记录"""
        commission_amount = order_amount * commission_rate / 100
        
        commission_record = BgAffiliateCommission(
            inviter_id=inviter_id,
            invitee_id=invitee_id,
            order_id=order_id,
            order_amount=order_amount,
            commission_rate=commission_rate,
            commission_amount=commission_amount,
            status=0,  # 待结算
            create_time=datetime.now(),
            update_time=datetime.now(),
            del_flag='0',
            create_by=inviter_id,
            dept_id=204
        )
        db.add(commission_record)
        if auto_commit:
            await db.commit()
        return commission_record

    async def get_by_order_id(self, db: AsyncSession, order_id: int) -> Optional[BgAffiliateCommission]:
        """根据订单ID获取返利记录"""
        result = await db.execute(
            select(BgAffiliateCommission).filter(
                BgAffiliateCommission.order_id == order_id,
                BgAffiliateCommission.del_flag == '0'
            )
        )
        return result.scalar_one_or_none()

    async def update_commission_status(self, db: AsyncSession, commission_id: int, status: int, settle_time: datetime = None):
        """更新返利记录状态"""
        update_data = {'status': status}
        if settle_time:
            update_data['settle_time'] = settle_time
            
        await db.execute(
            update(BgAffiliateCommission)
            .filter(
                BgAffiliateCommission.id == commission_id,
                BgAffiliateCommission.del_flag == '0'
            )
            .values(**update_data)
        )
        await db.commit()

    async def settle_commission(self, db: AsyncSession, commission_id: int):
        """结算返利"""
        await self.update_commission_status(db, commission_id, 1, datetime.now())

    async def cancel_commission(self, db: AsyncSession, commission_id: int):
        """取消返利"""
        await self.update_commission_status(db, commission_id, 2)
